package dilmaj.client;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import dilmaj.shared.AreaVO;
import dilmaj.shared.FieldVerifier;
import dilmaj.shared.StarEntryVO;
import dilmaj.shared.TermVO;
import dilmaj.shared.UserVO;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
//import com.google.gwt.widgetideas.client.CollapsiblePanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TestGWT implements EntryPoint {
	  private DilmajConstants constants = GWT.create(DilmajConstants.class);
	  
	  private String username=new String("");
	  private long userid;

	  private Button backupButton=new Button(constants.backup());
	  //private Button convertButton=new Button("convert");
	  
	  private VerticalPanel loginPanel = new VerticalPanel();
	  private PasswordTextBox passBox = new PasswordTextBox();
	  private Button loginButton = new Button(constants.login());
	  private TextBox userBox = new TextBox();
	  private Label loginMessage=new Label();
	  private Button logoutButton=new Button(constants.logout());
	  
	  AsyncCallback<UserVO> loginCallback = new AsyncCallback<UserVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
			  loginMessage.setText(caught.toString());
			  loginMessage.setVisible(true);
		  }
	
		  public void onSuccess(UserVO result) {
			  if (!result.getUsername().endsWith("error")) {
				DataStore.setLogin(result.getUsername(), result.getId());  
				  
			    username=result.getUsername();
			    logRefresh();

				myTerms.clear();
				Iterator iterator=allTerms.iterator();
				while (iterator.hasNext()) {
					TermVO currentTerm=(TermVO)iterator.next();
					
					if (currentTerm.getUserName().compareTo(username)==0) {
						myTerms.add(currentTerm);
					}
				}
				updateMyTermsTable();
			  } else {
				  loginMessage.setText(result.getUsername());
				  loginMessage.setVisible(true);
			  }
		  }
	  };
	  AsyncCallback<String> logoutCallback = new AsyncCallback<String>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(String result) {
		    username="";
		    logRefresh();
		    myTerms.clear();
		    DataStore.setLogin("", -1);
		  }
	  };
	  AsyncCallback<UserVO> getloginCallback = new AsyncCallback<UserVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(UserVO result) {
			if (result!=null) {
				username=result.getUsername();
				userid=result.getId();
			    DataStore.setLogin(username, userid);
			} else {
				username="";
			    DataStore.setLogin("", -1);
			}
		    logRefresh();

			myTerms.clear();
			Iterator iterator=allTerms.iterator();
			while (iterator.hasNext()) {
				TermVO currentTerm=(TermVO)iterator.next();
				
				if (currentTerm.getUserName().compareTo(username)==0) {
					myTerms.add(currentTerm);
				}
			}
			updateMyTermsTable();
		  }
	  };
	  AsyncCallback<AreaVO> addAreaCallback = new AsyncCallback<AreaVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(AreaVO result) {
			  updateAreaTable(result);
		  }
	  };
	  AsyncCallback<List<AreaVO>> loadAreaCallback = new AsyncCallback<List<AreaVO>>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(List<AreaVO> result) {
			  updateAreaTable(result);
		  }
	  };
	 // private FlexTable searchFlexTable=new FlexTable();
  
	  private VerticalPanel termsPanel = new VerticalPanel();
	  private ScrollPanel scrollPanel=new ScrollPanel();
	  private HorizontalPanel addPanel = new HorizontalPanel();
	  private FlexTable termsFlexTable = new FlexTable();
	  //private Button createButton = new Button(constants.create());
	  private TextBox entryField = new TextBox();
	  private Label termsLabel=new Label(constants.list()+" "+constants.terms());
	  // search panel
	  private Label filterLabel=new Label(constants.search());
	  private TextBox searchBox=new TextBox();
	  private Button searchButton=new Button(constants.search());
	  private HorizontalPanel filterPanel=new HorizontalPanel();
	  
	  // My list 
	  private VerticalPanel myTermsPanel = new VerticalPanel();
	  private ScrollPanel myScrollPanel=new ScrollPanel();
	  private HorizontalPanel myAddPanel = new HorizontalPanel();
	  private FlexTable myTermsFlexTable = new FlexTable();
	  private Button myCreateButton = new Button(constants.create());
	  private TextBox myEntryField = new TextBox();
	  private Label myTermsLabel=new Label(constants.list()+" "+constants.terms());

	  private FlexTable areasFlexTable=new FlexTable();
	  private VerticalPanel areasPanel = new VerticalPanel();
	  private HorizontalPanel addAreaPanel=new HorizontalPanel(); 
	  private Button createAreaButton = new Button(constants.create());
	  private TextBox newAreaField = new TextBox();
	  private Label areasLabel=new Label(constants.list()+" "+constants.areas());

	  private FlexTable userFlexTable=new FlexTable();
	  private VerticalPanel userPanel = new VerticalPanel();
	  private Label userLabel=new Label(constants.list()+" "+constants.personal()+" "+constants.terms());

	  private TermServiceAsync termSvc = GWT.create(TermService.class);
	  private UserServiceAsync userSvc = GWT.create(UserService.class);
	  private AreaServiceAsync areaSvc = GWT.create(AreaService.class);
	  private StarServiceAsync starSvc = GWT.create(StarService.class);
	  
	  private ArrayList<TermVO> allTerms=new ArrayList<TermVO>();
	  private ArrayList<TermVO> myTerms=new ArrayList<TermVO>();
	  private ArrayList<AreaVO> allAreas=new ArrayList<AreaVO>();

	  private ArrayList<TermVO> foundTerms=new ArrayList<TermVO>();
	  private ArrayList<String> foundTitles=new ArrayList<String>();
	  private SearchPanel searchPanel=new SearchPanel(this, foundTerms, foundTitles);

	  private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	  AsyncCallback<TermVO> updateCallback = new AsyncCallback<TermVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(TermVO result) {
			    int row=0;
			    Iterator iterator=allTerms.iterator();
			    while (iterator.hasNext()) {
			    	TermVO currentTerm=(TermVO)iterator.next();
			    	if (currentTerm.getId().intValue()==result.getId().intValue()) {
			    		row=allTerms.indexOf(currentTerm);
			    		currentTerm.setRank(result.getRank());
			    		currentTerm.setPrivilege(result.getPrivilege());
			    	}
			    }
				termsFlexTable.setText(row+1, 5, result.getRank()+"");
				termsFlexTable.setText(row+1, 9, result.getPrivilege()+"");
		  }
	  };
		
	  class BackupHandler implements ClickHandler {
		  public void onClick(ClickEvent event) {
              String link = GWT.getModuleBaseURL() + "dilmajData"; 
              RootPanel.get().add(new HTML("<a href=\"" + link + "\">Download File</a>")); 		  }
	  }
	  
	  AsyncCallback<List<StarEntryVO>> starCallback = new AsyncCallback<List<StarEntryVO>>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
			  backupButton.setText("failed");
		  }
	
		  public void onSuccess(List<StarEntryVO> result) {
			  backupButton.setText("done");
		  }
	  };
		

	  class ConvertHandler implements ClickHandler {
		  public void onClick(ClickEvent event) {
			  starSvc.convertAll(starCallback);
		  }
	  }
	  
	  class SearchHandler implements ClickHandler {
		  public void onClick(ClickEvent event) {
			  foundTerms.clear();
			  foundTitles.clear();
			  
			  int n=allTerms.size();/*termsFlexTable.getRowCount();
			  searchFlexTable.removeAllRows();*/
			  String filter=searchBox.getText().toLowerCase();
			  
			  for (int i=0;i<n;i++) {
				  TermVO termVO=allTerms.get(i);
				  String caption=termVO.getCaption().toLowerCase();//termsFlexTable.getText(i, 3).toLowerCase();
				  if (caption.indexOf(filter)!=-1) {
					  foundTerms.add(termVO);
					  foundTitles.add(i+1+"");
					  //int j=0;
					  
					  /*searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++)); //0
					  
					  Button button1=new Button("-");
					  button1.addClickHandler(new MinusHandler());
					  button1.setTitle(termsFlexTable.getWidget(i, j).getTitle());
					  searchFlexTable.setWidget(i, j++, button1);//1
					  
					  Button button2=new Button("+");
					  button2.addClickHandler(new PlusHandler());
					  button2.setTitle(termsFlexTable.getWidget(i, j).getTitle());
					  searchFlexTable.setWidget(i, j++, button2);//2
					  
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//3		
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//4
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//5
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//6
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//7
					  
					  Button button8=new Button(constants.usecase());
					  button8.addClickHandler(new UseCaseHandler(false));
					  button8.setTitle(termsFlexTable.getWidget(i, j).getTitle());
					  searchFlexTable.setWidget(i, j++, button8);//8
					  searchFlexTable.setText(i, j, termsFlexTable.getText(i, j++));//9
					  
					  Button button10=new Button(constants.comments());
					  button10.addClickHandler(new CommentsHandler());
					  button10.setTitle(termsFlexTable.getWidget(i, j).getTitle());
					  searchFlexTable.setWidget(i, j, button10);//10*/
				  }
			  }
			  
			  searchPanel.setSearchTable(foundTerms, foundTitles/*searchFlexTable*/);
			  searchPanel.show();
		  }
	  }
	  
	  class AddAreaHandler implements ClickHandler {
		  private boolean viewOnly;
		  
		  public AddAreaHandler(boolean isView) {
			  viewOnly=isView;
		  }
		  
		  public void onClick(ClickEvent event) {
			  int index=Integer.parseInt(((Button)event.getSource()).getTitle());
			  TermVO termVO=null;
			  if (viewOnly) {
				  termVO=allTerms.get(index);
			  } else {
				  termVO=myTerms.get(index);
			  }
			  AddAreasPanel panel=new AddAreasPanel(allAreas, termVO, viewOnly);
			  Button button=(Button)event.getSource();
			  int left=button.getAbsoluteLeft();
			  int top=button.getAbsoluteTop();
			  panel.setPopupPosition(left, top);
			  panel.show();
		  }
	  }
	  
	  class AreaHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
				addArea(newAreaField.getText());
			}
	  }
	  
		class MinusHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
			    if (termSvc == null) {
				      termSvc = GWT.create(TermService.class);
				    }
				Button button=(Button)event.getSource();
				int row=Integer.parseInt(button.getTitle());
				TermVO termVO=allTerms.get(row);
			    
			    if (username.compareTo("")==0 || termVO.getUserName().compareTo(username)!=0) {
			    	long rank=termVO.getRank().longValue();
			    	rank--;
			    	termVO.setRank(rank);
		    		if (termVO.getUsers().contains(username) && username.compareTo("")!=0) {
				    	MessagePanel panel=new MessagePanel("You've already privileged this item");
				    	int left=button.getAbsoluteLeft();
						int top=button.getAbsoluteTop();
						panel.setPopupPosition(left, top);
					    panel.show();
		    		} else if (username.compareTo("")!=0) {
				    	long privilege=termVO.getPrivilege().longValue();
				    	privilege--;
				    	termVO.setPrivilege(privilege);
				    	termVO.addUser(username);
		    		}
			    	termSvc.update(termVO, updateCallback);
			    } else {
			    	MessagePanel panel=new MessagePanel("You may not rank your own suggestions");
			    	int left=button.getAbsoluteLeft();
					int top=button.getAbsoluteTop();
					panel.setPopupPosition(left, top);
				    panel.show();
			    }
			}
		}
		
		class PlusHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
			    if (termSvc == null) {
				      termSvc = GWT.create(TermService.class);
				    }
				Button button=(Button)event.getSource();
				int row=Integer.parseInt(button.getTitle());
				TermVO termVO=allTerms.get(row);
			    
			    if (username.compareTo("")==0 || termVO.getUserName().compareTo(username)!=0) {
			    	long rank=termVO.getRank().longValue();
			    	rank++;
			    	termVO.setRank(rank);
			    	if (username.compareTo("")!=0) {
			    		if (termVO.getUsers().contains(username) && username.compareTo("")!=0) {
					    	MessagePanel panel=new MessagePanel("You've already privileged this item");
					    	int left=button.getAbsoluteLeft();
							int top=button.getAbsoluteTop();
							panel.setPopupPosition(left, top);
						    panel.show();
			    		} else if (username.compareTo("")!=0) {
					    	long privilege=termVO.getPrivilege().longValue();
					    	privilege++;
					    	termVO.setPrivilege(privilege);
					    	termVO.addUser(username);
			    		}
			    	}
			    	termSvc.update(termVO, updateCallback);
			    } else {
			    	MessagePanel panel=new MessagePanel("You may not rank your own suggestions");
			    	int left=button.getAbsoluteLeft();
					int top=button.getAbsoluteTop();
					panel.setPopupPosition(left, top);
				    panel.show();
			    }
			}
		}

		class CommentsHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
				  int index=Integer.parseInt(((Button)event.getSource()).getTitle());
				  TermVO termVO=null;
				  termVO=allTerms.get(index);
				  CommentPanel panel=new CommentPanel(termVO, username, userid);
				  Button button=(Button)event.getSource();
				  int left=button.getAbsoluteLeft();
				  int top=button.getAbsoluteTop();
				  panel.setPopupPosition(left, top);
				  panel.show();
			}
		}
		
		class SuggestionHandler implements ClickHandler {
			private boolean isEditable;
			private TestGWT owner;
			
			public SuggestionHandler(TestGWT owner, boolean isEditable) {
				this.isEditable=isEditable;
				this.owner=owner;
			}
			
			public void onClick(ClickEvent event) {
				  int index=Integer.parseInt(((Button)event.getSource()).getTitle());
				  TermVO termVO=null;
				  if (isEditable)
					  termVO=myTerms.get(index);
				  else
					  termVO=allTerms.get(index);
				  SuggestionPanel panel=new SuggestionPanel(owner, isEditable, termVO);
				  Button button=(Button)event.getSource();
				  int left=button.getAbsoluteLeft();
				  int top=button.getAbsoluteTop();
				  panel.setPopupPosition(left, top);
				  panel.show();
			}
		}
		
		class UseCaseHandler implements ClickHandler {
			private boolean isEditable;
			
			public UseCaseHandler(boolean isEditable) {
				this.isEditable=isEditable;
			}
			
			public void onClick(ClickEvent event) {
				  int index=Integer.parseInt(((Button)event.getSource()).getTitle());
				  TermVO termVO=null;
				  if (isEditable)
					  termVO=myTerms.get(index);
				  else
					  termVO=allTerms.get(index);
				  UseCasePanel panel=new UseCasePanel(isEditable, termVO);
				  Button button=(Button)event.getSource();
				  int left=button.getAbsoluteLeft();
				  int top=button.getAbsoluteTop();
				  panel.setPopupPosition(left, top);
				  panel.show();
			}
		}
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private void loadAllTerms() {
	    // Initialize the service proxy.
	    if (termSvc == null) {
	      termSvc = GWT.create(TermService.class);
	    }

	    // Set up the callback object.
	    AsyncCallback<List<TermVO>> callback = new AsyncCallback<List<TermVO>>() {
	      public void onFailure(Throwable caught) {
	        // TODO: Do something with errors.
	    	  entryField.setText(caught.toString());
	      }

	      public void onSuccess(List<TermVO> result) {
	        updateTermsTable(result);
	      }
	    };

	    // Make the call to the stock price service.
	    //termSvc.getAllTerms(callback);
	    termSvc.getAllJDOTerms(callback);
	}
	
	  private void updateMyTermsTable() {
	  	myTermsFlexTable.setText(0, 0, constants.id());
	  	myTermsFlexTable.setText(0, 1, constants.caption());
	  	myTermsFlexTable.setText(0, 2, constants.rank());
	  	myTermsFlexTable.setText(0, 3, constants.areas());
	  	myTermsFlexTable.setText(0, 4, constants.suggestion());
	  	myTermsFlexTable.setText(0, 5, constants.usecase());
	  	myTermsFlexTable.setText(0, 6, constants.privilege());
	  	//Collections.reverse(terms);
	  	Iterator iterator=myTerms.iterator();
	  	int row=1;
	  	while (iterator.hasNext()) {
	  		TermVO termVO=(TermVO)iterator.next();
	  		
		    myTermsFlexTable.setText(row, 0, termVO.getId()+"");
		    myTermsFlexTable.setText(row, 1, termVO.getCaption());
		    myTermsFlexTable.setText(row, 2, termVO.getRank()+"");
		    
		    Button areasButton=new Button(constants.areas());
		    areasButton.setTitle(row-1+"");
		    areasButton.addClickHandler(new AddAreaHandler(false));
		    myTermsFlexTable.setWidget(row, 3, areasButton);
		    
		    Button suggestionButton=new Button(constants.suggestion());
		    suggestionButton.setTitle(row-1+"");
		    suggestionButton.addClickHandler(new SuggestionHandler(this, true));
		    myTermsFlexTable.setWidget(row, 4, suggestionButton);
		    
		    Button useButton=new Button(constants.usecase());
		    useButton.setTitle(row-1+"");
		    useButton.addClickHandler(new UseCaseHandler(true));
		    myTermsFlexTable.setWidget(row, 5, useButton);
		    
		    myTermsFlexTable.setText(row, 6, termVO.getPrivilege()+"");
		    
	  		row++;
	  	}
	  }
	  
	  private void updateTermsTable(List<TermVO> terms) {
		  	termsFlexTable.setText(0, 0, constants.id());
		  	termsFlexTable.setText(0, 1, "-");
		  	termsFlexTable.setText(0, 2, "+");
		  	termsFlexTable.setText(0, 3, constants.caption());
		  	termsFlexTable.setText(0, 4, constants.suggestion());
		  	termsFlexTable.setText(0, 5, constants.rank());
		  	termsFlexTable.setText(0, 6, constants.user());
		  	termsFlexTable.setText(0, 7, constants.areas());
		  	termsFlexTable.setText(0, 8, constants.usecase());
		  	termsFlexTable.setText(0, 9, constants.privilege());
		  	//termsFlexTable.setText(0, 8, "usecase");
		  	Collections.reverse(terms);
		  	Iterator iterator=terms.iterator();
		  	while (iterator.hasNext()) {
		  		TermVO currentTerm=(TermVO)iterator.next();
		  		updateTermRow(currentTerm, false);
		  	}
		  }
	  
	  public void updateTermRow(TermVO termVO, boolean byID) {
		  int row;
		  
		  if (!byID) {
		  	if (!allTerms.contains(termVO)) {
		  		allTerms.add(termVO);
		  	}
		    row = allTerms.indexOf(termVO) + 1;
		  } else {
			row=-1;
			Iterator iterator=allTerms.iterator();
			while (iterator.hasNext() && row==-1) {
				TermVO currentTerm=(TermVO)iterator.next();
				if (currentTerm.getId().longValue()==termVO.getId().longValue()) {
				    row = allTerms.indexOf(currentTerm) + 1;
				}
			}
		  }
		  	
		    
		    Button plusButton=new Button("+");
		    plusButton.setTitle(row-1+"");
		    plusButton.addClickHandler(new PlusHandler());
		    Button minusButton=new Button("-");
		    minusButton.setTitle(row-1+"");
		    minusButton.addClickHandler(new MinusHandler());
		    termsFlexTable.setText(row, 0, termVO.getId()+"");
		    termsFlexTable.setWidget(row, 1, minusButton);
		    termsFlexTable.setWidget(row, 2, plusButton);
		    termsFlexTable.setText(row, 3, termVO.getCaption());
		    termsFlexTable.setText(row, 4, termVO.getSuggestion());
		    termsFlexTable.setText(row, 5, termVO.getRank()+"");
		    
		    String username=termVO.getUserName();
		    if (username==null)
		    	username="";
		    termsFlexTable.setText(row, 6, username);
		    
		    /*String areas="";
		    Iterator iterator=termVO.getAreas().iterator();
		    while (iterator.hasNext()) {
		    	Long areaID=(Long)iterator.next();
		    	
		    	Iterator iterator1=allAreas.iterator();
		    	while (iterator1.hasNext()) {
		    		AreaVO areaVO=(AreaVO)iterator1.next();
		    		if (areaVO.getId().longValue()==areaID.longValue()) {
		    			areas=areas.concat(areaVO.getCaption()).concat(", ");
		    		}
		    	}
		    }
		    termsFlexTable.setText(row, 7, areas);*/
		    
		    Button areasButton=new Button(constants.areas());
		    areasButton.setTitle(row-1+"");
		    areasButton.addClickHandler(new AddAreaHandler(true));
		    termsFlexTable.setWidget(row, 7, areasButton);
		    
		    Button viewUseCase=new Button(constants.usecase());
		    viewUseCase.setTitle(row-1+"");
		    viewUseCase.addClickHandler(new UseCaseHandler(false));
		    termsFlexTable.setWidget(row, 8, viewUseCase);
		    
		    termsFlexTable.setText(row, 9, termVO.getPrivilege()+"");

		    Button commentsButton=new Button(constants.comments());
		    commentsButton.setTitle(row-1+"");
		    commentsButton.addClickHandler(new CommentsHandler());
		    termsFlexTable.setWidget(row, 10, commentsButton);
		  }
	  
	  public void updateMyTermRow(TermVO termVO) {
		updateTermRow(termVO, false);
		
	  	if (!myTerms.contains(termVO))
	  		myTerms.add(termVO);
	  	
	    int row = myTerms.indexOf(termVO) + 1;
	    
	    myTermsFlexTable.setText(row, 0, termVO.getId()+"");
	    myTermsFlexTable.setText(row, 1, termVO.getCaption());
	    myTermsFlexTable.setText(row, 2, termVO.getRank()+"");
	    
	    Button areasButton=new Button(constants.areas());
	    areasButton.setTitle(row-1+"");
	    areasButton.addClickHandler(new AddAreaHandler(false));
	    myTermsFlexTable.setWidget(row, 3, areasButton);
	    
	    Button suggestionButton=new Button(constants.suggestion());
	    suggestionButton.setTitle(row-1+"");
	    suggestionButton.addClickHandler(new SuggestionHandler(this, true));
	    myTermsFlexTable.setWidget(row, 4, suggestionButton);
	    
	    Button useButton=new Button(constants.usecase());
	    useButton.setTitle(row-1+"");
	    useButton.addClickHandler(new UseCaseHandler(true));
	    myTermsFlexTable.setWidget(row, 5, useButton);
	  }
	  
	  private void updateAreaTable(List<AreaVO> areas) {
	  	Iterator iterator=areas.iterator();
	  	while (iterator.hasNext()) {
	  		AreaVO currentArea=(AreaVO)iterator.next();
	  		updateAreaTable(currentArea);
	  	}
	  }
	  
	  private void updateAreaTable(AreaVO areaVO) {
		  if (!allAreas.contains(areaVO))
			  allAreas.add(areaVO);
		  
		  int row=allAreas.indexOf(areaVO)+1;
		  
		  areasFlexTable.setText(row, 0 ,areaVO.getId()+"");
		  areasFlexTable.setText(row, 1, areaVO.getCaption());
	  }

	/**
	 * This is the entry point method.
	 */
	private void login() {
	    if (userSvc == null) {
		      userSvc = GWT.create(UserService.class);
		    }
	    
	    userSvc.login(userBox.getText(), passBox.getText(), loginCallback);
	}
	
	private void logout() {
	    if (userSvc == null) {
		      userSvc = GWT.create(UserService.class);
		    }
	    
	    userSvc.logout(logoutCallback);
	}
	
	private void logRefresh() {
		if (username.compareTo("")==0) {
		    //termsPanel.setVisible(false);
		    areasPanel.setVisible(false);
		    loginPanel.setVisible(true);
		    userBox.setVisible(true);
		    passBox.setVisible(true);
		    userBox.setText("");
		    passBox.setText("");
		    loginButton.setVisible(true);
		    loginMessage.setVisible(false);
		    logoutButton.setVisible(false);
		    userPanel.setVisible(false);
		    myScrollPanel.setVisible(false);
		} else {
		    loginMessage.setText(constants.welcome()+" "+username+"!");
	        //termsPanel.setVisible(true);
	        areasPanel.setVisible(true);
		    loginMessage.setVisible(true);
		    userBox.setVisible(false);
		    passBox.setVisible(false);
		    loginButton.setVisible(false);
		    logoutButton.setVisible(true);
		    userPanel.setVisible(true);
		    myScrollPanel.setVisible(true);
		}
	  	
		/*int left=termsPanel.getAbsoluteLeft();
		int right=createButton.getAbsoluteLeft();
	  	scrollPanel.setSize(termsPanel.getOffsetWidth()+100right-left+"px", "300px");*/
	}
	
	public void onModuleLoad() {
	    termsFlexTable.setText(0, 0, constants.caption());
	    loginPanel.add(userBox);
	    loginPanel.add(passBox);
	    loginPanel.add(loginButton);
	    loginPanel.add(loginMessage);
	    loginPanel.add(logoutButton);
	    loginPanel.add(backupButton);
	    //loginPanel.add(convertButton);
	    backupButton.addClickHandler(new BackupHandler());
	    //convertButton.addClickHandler(new ConvertHandler());
	    
	    // Assemble Add Stock panel.
	    //addPanel.add(entryField);
	    //addPanel.add(createButton);
	    // Assemble Main panel.
	    termsPanel.add(filterPanel);
	    termsPanel.add(addPanel);
	    termsPanel.add(termsLabel);
	    termsPanel.add(termsFlexTable);
	    filterPanel.add(filterLabel);
	    filterPanel.add(searchBox);
	    filterPanel.add(searchButton);
	    scrollPanel.setSize("600px", "300px");
	    scrollPanel.add(termsPanel);
	    
	    // my terms panel.
	    myAddPanel.add(myEntryField);
	    myAddPanel.add(myCreateButton);
	    myTermsPanel.add(myAddPanel);
	    myTermsPanel.add(myTermsLabel);
	    myTermsPanel.add(myTermsFlexTable);
	    myScrollPanel.setSize("500px", "300px");
	    myScrollPanel.add(myTermsPanel);

	    addAreaPanel.add(newAreaField);
	    addAreaPanel.add(createAreaButton);
	    areasPanel.add(areasLabel);
	    areasPanel.add(areasFlexTable);
	    areasPanel.add(addAreaPanel);
	    
	    // Associate the Main panel with the HTML host page.
	    //RootPanel.get("termsList").add(scrollPanel);
	    //RootPanel.get("myList").add(myScrollPanel);
	    //RootPanel.get("areasList").add(areasPanel);
	    RootPanel.get("loginPanel").add(loginPanel);

	    if (userSvc == null) {
		      userSvc = GWT.create(UserService.class);
		    }
	    
	    userSvc.getLogin(getloginCallback);

	    DataStore.installDataStore();
	    StarTablePanel starPanel=new StarTablePanel(new String[0], constants.term(), false, null, null);
	    RootPanel.get("starDesign").add(starPanel);
	    DataStore.openPanel(starPanel);
	    
	    HorizontalPanel descriptionPanel=new HorizontalPanel();
	    descriptionPanel.setWidth("300px");
	    descriptionPanel.add(new Label(constants.describeProject()));
	    RootPanel.get("projectDescription").add(descriptionPanel);

	    // Move cursor focus to the input box.
	    entryField.setFocus(true);
	    
		termsFlexTable.setText(0, 0, constants.caption());
		
		entryField.setText("Enter a term here ...");
		//errorField.setText("No Error");

		// We can add style names to widgets
		//myCreateButton.addStyleName("sendButton");
		loginButton.addStyleName("sendButton");

		/*loadAllTerms();
		loadAllAreas();*/
		
	    
		class LoginHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
				login();
			}
		}
		
		class LogoutHandler implements ClickHandler {
			public void onClick(ClickEvent event) {
				logout();
			}
		}
		
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
				//getConn();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer() {
				String textToServer = myEntryField.getText();
				
			    if (termSvc == null) {
				      termSvc = GWT.create(TermService.class);
				    }

				termSvc.addTerm(new TermVO(textToServer, 0), new AsyncCallback<TermVO>() {
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						//errorLabel.setText(caught.toString());
					}

					@Override
					public void onSuccess(TermVO result) {
						// TODO Auto-generated method stub
						updateMyTermRow(result);
					    
					    //scrollPanel.scrollToBottom();
					    myScrollPanel.scrollToBottom();

						//termsFlexTable.clear();
						//loadAllTerms();
					}
					}
				);
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		myCreateButton.addClickHandler(handler);
		createAreaButton.addClickHandler(new AreaHandler());
		entryField.addKeyUpHandler(handler);
		loginButton.addClickHandler(new LoginHandler());
		logoutButton.addClickHandler(new LogoutHandler());
		searchButton.addClickHandler(new SearchHandler());
	}
	
	private void addArea(String areaCaption) {
	    if (areaSvc == null) {
		      areaSvc = GWT.create(AreaService.class);
	    }
	    
	    areaSvc.addArea(new AreaVO(areaCaption), addAreaCallback);
	}
	
	private void loadAllAreas() {
	    // Initialize the service proxy.
	    if (areaSvc == null) {
	      areaSvc = GWT.create(AreaService.class);
	    }
	    
	    areaSvc.getAllAreas(loadAreaCallback);
	}
}
